package com.lifo.utils;


import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * Created by Administrator on 2018/7/2 0002.
 */
public class FunctionProgrammeUtils {
    /**
     * 对list中存储的对象进行去重（函数式编程，真的很难理解）
     * final Collection<HfShoppingCart> lists = FunctionProgrammeUtils.distinct(list,HfShoppingCart::getShopId);
     * @param collection 需要去重的list
     * @param fn 需要
     * @param <T> 函数输入的参数
     * @param <R> 函数返回的结果
     * @return
     */
    public static  <T, R> Collection<T> distinct(Collection<T> collection, Function<T, R> fn) {
        Map<R, T> map = new HashMap<>(collection.size());
        for (T t : collection) {
            map.putIfAbsent(fn.apply(t), t);
        }
        return map.values();
    }
}
